<style scoped lang="less">
.progressBar {
  position: relative;
  width: 100%;
  cursor: pointer;
  &__trunk{
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: v-bind(trunkColorCom);
  }
  &__bar{
    width: v-bind(valueRatio);
    height: 100%;
    background: v-bind(barColorCom);
    position: absolute;
    left: 0;
    top: 0;
    z-index: 10;
  }
}
</style>
<template>
  <div class="progressBar" ref="progress" @click="handleClick">
    <div class="progressBar__trunk" />
    <div class="progressBar__bar" />
  </div>
</template>

<script lang="ts" setup>
import {computed, ref} from "vue";
import {getDomPosition, getPointerPosition,formatDuring} from "@/helper"

const props = defineProps({
  max:{ type:[Number,String], default:0 },
  value:{ type:[Number,String], default:0 },
  barColor:{ type:[String] },
  trunkColor:{ type:[String] },
  isTimeFormat:{ type:[Boolean], default:false },
})
const emit = defineEmits(['update:value'])

const barColorCom = computed(() => props?.barColor ?? '#d1240c') // 进度条颜色
const trunkColorCom = computed(() => props?.trunkColor ?? '#f3edf1') // 进度条背景颜色
const isTimeFormat = computed(() => props?.isTimeFormat ?? false) // 是否是时间格式
const maxValue = computed(() => props.isTimeFormat ? parseTime(props?.max ?? '') : checkValue(props?.max ?? ''))
const valueRatio = computed(() => { // 当前值占最大值的百分比
  const value = props.isTimeFormat ? parseTime(props?.value ?? '') : checkValue(props?.value ?? '')
  return (value * 100 / (maxValue.value || 1)).toFixed(2) + '%'
})
const progress = ref(null) // ref
/** 检查数字 */
const checkValue = (value:number | string):number => {
  const valueRelative = Number(value)
  if(isNaN(valueRelative)) return 0
  else return valueRelative
}
/** 解析时间 */
const parseTime = (time:string):number => {
  if(!time || !time.includes(':') ) return 0
  const [minute,second] = time.split(':').map(item => Number(item))
  if (isNaN(minute) || isNaN(second)) return 0
  return minute * 60 + second
}
/** 点击进度 */
const handleClick = (event:MouseEvent) => {
  const { x } = getPointerPosition(event)
  const { left, width } = getDomPosition(progress.value,false)
  const ratio = (x - left)/ width
  const value = isTimeFormat ? formatDuring(ratio * maxValue.value,'{M}:{S}') : ratio * maxValue.value
  emit('update:value', value)
}
</script>

